<template>
  <el-card class="content-section">
    <div class="section-header">
      <div class="section-info">
        <h2 class="section-title">各医院标签使用情况分析</h2>
      </div>
      <div class="update-info">
        <el-button type="primary" icon="el-icon-download" size="mini" @click="exportData">导出数据</el-button>
        <span class="update-frequency" @click="refreshData">每日更新</span>
        <span class="last-updated">更新于: {{ updateTime }}</span>
      </div>
    </div>

    <el-tabs v-model="activeTab">
      <el-tab-pane label="按标签查看" name="tag">
        <el-table :data="tagList" style="width: 100%" @sort-change="handleSortChange">
          <el-table-column prop="tagName" label="标签名称" min-width="120">
            <template slot-scope="scope">
              <span class="tooltip">
                <span>{{ scope.row.tagName }}</span>
                <span class="tooltip-text">标签的具体名字，例如"高血压"、"术后康复"、"VIP客户"等</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="hospitalQuantity" label="使用医院数" sortable="custom" min-width="120">
            <template slot="header">
              <span>使用医院数</span>
              <el-tooltip content="核心平台指标，统计了在全平台上有多少家不同的医院都创建了这个完全同名的标签" placement="top">
                <i class="el-icon-question tooltip-icon"></i>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="coverCustomer" label="覆盖总患者数" sortable="custom" min-width="140">
            <template slot="header">
              <span>覆盖总患者数</span>
              <el-tooltip content="在所有使用了该标签的医院中，这个标签总共覆盖了多少去重的患者人数" placement="top">
                <i class="el-icon-question tooltip-icon"></i>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="avgCoverCustomer" label="平均覆盖患者数" sortable="custom" min-width="140">
            <template slot="header">
              <span>平均覆盖患者数</span>
              <el-tooltip content="覆盖总患者数 / 使用医院数，反映了单个医院在使用这个标签时的平均深度" placement="top">
                <i class="el-icon-question tooltip-icon"></i>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="lastUsedTime" label="最后使用时间" sortable="custom" min-width="140">
            <template slot="header">
              <span>最后使用时间</span>
              <el-tooltip content="该标签在全平台范围内，最近一次被使用的时间" placement="top">
                <i class="el-icon-question tooltip-icon"></i>
              </el-tooltip>
            </template>
            <template slot-scope="scope">
              {{ scope.row.lastUsedTime || '--' }}
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-container">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="pagination.currentPage" :page-sizes="[5, 10, 20, 50]" :page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="pagination.total">
          </el-pagination>
        </div>
      </el-tab-pane>
      <el-tab-pane label="按标签组查看" name="group">
        <el-table :data="tagGroupList" style="width: 100%" @sort-change="handleSortChange">
          <el-table-column prop="groupName" label="标签组名称" min-width="120">
            <template slot-scope="scope">
              <span class="tooltip">
                <span>{{ scope.row.groupName }}</span>
                <span class="tooltip-text">标签组的名字，例如"按付费类型"、"按病种类"、"按患者来源"等</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="hospitalQuantity" label="使用医院数" sortable="custom" min-width="120">
            <template slot="header">
              <span>使用医院数</span>
              <el-tooltip content="核心平台指标，统计了在全平台上有多少家不同的医院都创建了这个完全同名的标签" placement="top">
                <i class="el-icon-question tooltip-icon"></i>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="tagQuantity" label="标签总数" sortable="custom" min-width="120">
            <template slot="header">
              <span>标签总数</span>
              <el-tooltip content="该标签组下所有去重标签数总数" placement="top">
                <i class="el-icon-question tooltip-icon"></i>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="avgTagQuantity" label="平均标签数" sortable="custom" min-width="120">
            <template slot="header">
              <span>平均标签数</span>
              <el-tooltip content="该标签组下所有去重标签数/使用医院数，反映了该标签组下平均包含了多少个具体的标签" placement="top">
                <i class="el-icon-question tooltip-icon"></i>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="coverCustomer" label="覆盖总患者数" sortable="custom" min-width="140">
            <template slot="header">
              <span>覆盖总患者数</span>
              <el-tooltip content="该标签组下的所有标签，在全平台覆盖的去重患者总数" placement="top">
                <i class="el-icon-question tooltip-icon"></i>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="avgCoverCustomer" label="平均覆盖患者数" sortable="custom" min-width="140">
            <template slot="header">
              <span>平均覆盖患者数</span>
              <el-tooltip content="覆盖总患者数 / 使用医院数，反映了单个医院在使用这个标签组时的平均深度" placement="top">
                <i class="el-icon-question tooltip-icon"></i>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="lastUsedTime" label="最后使用时间" sortable="custom" min-width="140">
            <template slot="header">
              <span>最后使用时间</span>
              <el-tooltip content="该标签组下的任意一个标签，在全平台范围内最近一次被使用的时间" placement="top">
                <i class="el-icon-question tooltip-icon"></i>
              </el-tooltip>
            </template>
            <template slot-scope="scope">
              {{ scope.row.lastUsedTime || '--' }}
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-container">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="pagination.currentPage" :page-sizes="[5, 10, 20, 50]" :page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="pagination.total">
          </el-pagination>
        </div>
      </el-tab-pane>
    </el-tabs>
  </el-card>
</template>

<script>
import { getEachHospitalTagSituation, getEachHospitalTagGroupSituation } from '@/api/chenlong.js'
export default {
  name: 'TagAnalysis',
  data() {
    return {
      activeTab: 'tag',  // tag: 按标签查看, group: 按标签组查看
      // 分页信息
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      tagList: [],
      tagGroupList: [],
      updateTime: '--',
      sorting: '',  //排序字段
      sortType: ''  //sortType排序方式 desc asc
    }
  },
  mounted() {
    this.getData()
  },
  watch: {
    activeTab: {
      handler(newVal, oldVal) {
        if (newVal !== oldVal) {
          this.sorting = ''
          this.sortType = ''
          this.pagination.currentPage = 1
          this.getData()
        }
      }
    }
  },
  methods: {
    async getData(refresh = false) {
      const params = {
        pageSize: this.pagination.pageSize,
        pageNum: this.pagination.currentPage
      }
      if (refresh) {
        params.refresh = 'refresh'
      }
      // 添加排序参数
      if (this.sorting && this.sortType) {
        params.sorting = this.sorting
        params.sortType = this.sortType
      }

      try {
        let res
        if (this.activeTab === 'tag') {
          res = await getEachHospitalTagSituation(params)
        } else {
          res = await getEachHospitalTagGroupSituation(params)
        }

        if (res.code == 200) {
          if (this.activeTab === 'tag') {
            this.tagList = res.data.list || []
            this.pagination.total = res.data.total || 0
          } else {
            this.tagGroupList = res.data.list || []
            this.pagination.total = res.data.total || 0

            // {
            //     "tagName": "1805同事",  //标签名称
            //     "hospitalQuantity": 1,  //使用医院数
            //     "coverCustomer": 0,    //覆盖总患者数
            //     "avgCoverCustomer": "0.00",  //平均覆盖患者数
            //     "lastUsedTime": ""  //最后使用时间
            // },

          }
          this.updateTime = res.data.updateTime || this.formatCurrentTime()
        }
      } catch (error) {
        console.error('获取数据失败:', error)
      }
    },
    async refreshData() {
      try {
        await this.getData(true)
        this.$message.success('数据更新成功')
      } catch (error) {
        this.$message.error('数据更新失败，请重试')
      }
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.pagination.currentPage = 1
      this.getData()
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.getData()
    },
    formatCurrentTime() {
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      const day = String(now.getDate()).padStart(2, '0')
      const hours = String(now.getHours()).padStart(2, '0')
      const minutes = String(now.getMinutes()).padStart(2, '0')
      return `${year}.${month}.${day} ${hours}:${minutes}`
    },
    // 表格排序变化处理
    async handleSortChange({ column, prop, order }) {
      if (order === null) {
        // 取消排序
        this.sorting = ''
        this.sortType = ''
      } else {
        // 设置排序字段和排序方式
        this.sorting = prop
        this.sortType = order === 'ascending' ? 'asc' : 'desc'
      }

      // 重置到第一页
      this.pagination.currentPage = 1

      // 重新获取数据
      try {
        await this.getData()
        this.$message.success('排序成功')
      } catch (error) {
        this.$message.error('排序失败，请重试')
      }
    },
    // 导出数据
    exportData() {
      // 根据当前标签页生成不同的文件名
      const today = new Date()
      const year = today.getFullYear()
      const month = String(today.getMonth() + 1).padStart(2, '0')
      const day = String(today.getDate()).padStart(2, '0')
      const fileName = this.activeTab === 'tag' 
        ? `各医院标签使用情况分析_按标签查看_${year}${month}${day}.xlsx`
        : `各医院标签使用情况分析_按标签组查看_${year}${month}${day}.xlsx`
      
      // 构建导出参数
      const params = {
        // pageSize: this.pagination.pageSize,
        // pageNum: this.pagination.currentPage
      }
      
      // 添加排序参数
      if (this.sorting && this.sortType) {
        params.sorting = this.sorting
        params.sortType = this.sortType
      }
      
      if( this.activeTab == 'tag' ){
        this.download('/business/data/statistics/exportEachHospitalTagSituation', params, fileName)
      }else{
        this.download('/business/data/statistics/exportEachHospitalTagGroupSituation', params, fileName)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.content-section {
  background: #ffffff;
  border-radius: 8px;
  padding: 20px 20px 0 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  margin-bottom: 24px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #dddddd;
}

.section-title {
  font-size: 23px;
  font-weight: 600;
  margin: 0;
  border-left: 4px solid #4a90e2;
  padding-left: 12px;
}

.update-info {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #888888;
  font-size: 12px;
}

.update-frequency {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 2px 8px;
  background: rgba(74, 144, 226, 0.1);
  border-radius: 4px;
  white-space: nowrap;
  font-size: 16px;
  line-height: 1;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;

  &:hover {
    background-color: #409eff;
    color: #ffffff;
    transform: scale(1.05);
  }
}

.update-frequency::before {
  content: "⟳";
  font-size: 17px;
}

.last-updated {
  font-size: 15px;
  white-space: nowrap;
}

.el-button+.el-button {
  margin-left: 0;
}

.tooltip-icon {
  color: #4a90e2;
  cursor: help;
  margin-left: 4px;
}

.tooltip {
  position: relative;
  display: inline-block;
}

.tooltip .tooltip-text {
  visibility: hidden;
  width: 200px;
  background-color: #333;
  color: #fff;
  text-align: left;
  border-radius: 4px;
  padding: 8px;
  position: absolute;
  z-index: 1;
  bottom: 125%;
  left: 50%;
  transform: translateX(-50%);
  opacity: 0;
  transition: opacity 0.3s;
  font-size: 15px;
  line-height: 1.4;
}

.tooltip:hover .tooltip-text {
  visibility: visible;
  opacity: 1;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
  margin-bottom: 30px;

  /* ====== 加大 el-pagination 分页组件内所有文字的字号 ====== */
  ::v-deep .el-pagination {
    font-size: 16px;
  }

  /* 页码按钮（比如 1 2 3 4 5 ...） */
  ::v-deep .el-pagination .el-pager li {
    font-size: 16px !important;
    min-width: 32px;
    height: 32px;
    line-height: 32px;
  }

  /* 上一页 / 下一页 按钮 */
  ::v-deep .el-pagination .btn-prev,
  ::v-deep .el-pagination .btn-next {
    font-size: 16px !important;
    min-width: 32px;
    height: 32px;
    line-height: 32px;
  }

  /* 总条数（比如：共 100 条） */
  ::v-deep .el-pagination .el-pagination__total {
    font-size: 16px !important;
    line-height: 2.2;
  }

  /* 每页条数选择器（sizes）的文本和按钮 */
  ::v-deep .el-pagination .el-pagination__sizes {
    font-size: 16px !important;
  }

  ::v-deep .el-pagination .el-pagination__sizes .el-input .el-input__inner {
    font-size: 16px !important;
    height: 32px;
  }

  /* 跳转至输入框（比如：跳至 1 页） */
  ::v-deep .el-pagination .el-pagination__jump {
    font-size: 16px !important;
    line-height: 2.2;
  }

  ::v-deep .el-pagination .el-pagination__jump .el-input .el-input__inner {
    font-size: 16px !important;
    height: 32px;
  }

  /* 当前选中页码样式（可选美化） */
  ::v-deep .el-pagination .el-pager li.active {
    font-size: 16px !important;
    font-weight: 600;
    color: #409eff;
  }
}

/* ======================== 新增：表格内字体加大 3px ======================== */
/* 表头 th 字体 */
::v-deep .el-table .el-table__header th {
  font-size: 17px !important;
  font-weight: 600;
  color: #303133;
}

/* 表格单元格 td 字体 */
::v-deep .el-table .el-table__body td {
  font-size: 17px !important;
  color: #606266;
}

::v-deep .el-tabs__item {
  font-size: 18px !important;
  font-weight: 500;
}

::v-deep .el-tabs__item.is-active {
  font-size: 18px !important;
  font-weight: 600;
  color: #409eff;
}
</style>
